(function (global, undefined) {
    global.locMemory = {};
    global.locMemory.localStorage = {
        setItem: function (key, value, cb) {
            value = JSON.stringify(value);
            value = value || '';
            localStorage.setItem(`${key}`, `${value}`);
            cb && cb();
            return value;
        },
        getItem: function (key, cb) {
            value = localStorage.getItem(key) || '';
            value = value == '' ? '' : JSON.parse(value);
            cb && cb(null, value);
            return value;
        },
        removeItem: function (key, cb) {
            localStorage.removeItem(key);
            cb && cb();
        },
        clear: function (cb) {
            localStorage.clear();
            cb && cb();
        }
    }
}(window))

function wxAuthorize() {
    let link = window.location.href;
    let params = getUrlParam('code'); // 地址解析  
    let token = getUrlParam('share_token')
    let type = getUrlParam('item_type')
    localStorage.token = token
    localStorage.type = type
    // console.log("token:", token);
    // 如果拿到code，调用授权接口，没有拿到就跳转微信授权链接获取  
    if (localStorage.user_token) {
        //如果获取到  share_token 进行分享处理
        if (token) {
            request('share_help/', {
                zm_token: localStorage.user_token,
                _zm_post_type: 'ajax',
                share_token:  token,
                item_type:  type,
            }).then(() => {
                localStorage.setItem('token', '')
                localStorage.setItem('type', '')
                if (res.errno == 505) {
                    let appid = 'wx41fa84947dc4d128';
                    let uri = encodeURIComponent(link);
                    let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
                    window.location.href = authURL;
                }
            })
        }
        //获取当前分数情况
        refresh_settings();

        return
    } else {
        /*
        if (params) {
            // console.log("获取到code");
            request('user_auth/', {
                code: params
            }).then(res => {
                alert(JSON.stringify(res.rsm),'地址:user_auth')
                localStorage.setItem('userInfo', JSON.stringify(res.rsm))
                let token = res.rsm.zm_token
                request('refresh_settings/', {
                    zm_token: token,
                    _zm_post_type: 'ajax'
                }).then(res => {
                    alert(JSON.stringify(res.rsm),'地址:refresh_settings/',)
                    let gameStore = res.rsm
                    request('refresh_user_score/', {
                        zm_token: token,
                        _zm_post_type: 'ajax'
                    }).then(res => {
                        console.log(res.rsm);
                        let userScore = res.rsm
                        //  记得清除
                        // if (localStorage.getItem('game1')) {
                        //     return
                        // } else {
                        let obj1 = {
                            score: userScore.tree_score, //游戏得分
                            active: userScore.tree_score >= gameStore.tree_score, //是否通关
                            luck: gameStore.tree_lottery == 1, //是否抽奖
                            number: 0 //是否是第一次进入游戏
                        }
                        let obj2 = {
                            score: userScore.jump_score, //游戏得分
                            active: userScore.jump_score >= gameStore.jump_score, //是否通关
                            luck: gameStore.tree_lottery == 1, //是否抽奖
                            number: 0 //是否是第一次进入游戏
                        }
                        let obj3 = {
                            score: userScore.dance_score, //游戏得分
                            active: userScore.dance_score >= gameStore.dance_score, //是否通关
                            luck: gameStore.dance_lottery == 1, //是否抽奖
                            number: 0 //是否是第一次进入游戏
                        }
                        obj1 = JSON.stringify(obj1)
                        obj2 = JSON.stringify(obj2)
                        obj3 = JSON.stringify(obj3)
                        localStorage.setItem('game1', obj1)
                        localStorage.setItem('game2', obj2)
                        localStorage.setItem('game3', obj3)
                        localStorage.setItem('gift', gameStore.top_lottery == 1)
                        // }
                        if (locMemory.localStorage.getItem('token') != '') {
                            request('share_help/', {
                                zm_token: localStorage.user_token,
                                _zm_post_type: 'ajax',
                                share_token: locMemory.localStorage.getItem('token'),
                                item_type: locMemory.localStorage.getItem('type'),
                            }).then(() => {
                                locMemory.localStorage.setItem('token', '')
                                locMemory.localStorage.setItem('type', '')
                            })
                        }
                    })
                })
            })

            // api.wxAuth(params); // 调用后台接口，授权   
        } else {
            console.log("没有code");
            let token = getUrlParam('share_token')
            let type = getUrlParam('item_type')
            locMemory.localStorage.setItem('token', token || '')
            locMemory.localStorage.setItem('type', type || '')
            let appid = 'wx41fa84947dc4d128'; //修改为你的appid
            //1.使用encodeURIComponent以及JSON.stringify()方法对对象进行字符串化和编码，这样可以控制url参数的长度，参考示例代码（uni-app书写方式，微信小程序自己改。）  
            let uri = encodeURIComponent(link);

            //2.接受信息的页面使用JSON.parse()以及decodeURIComponent()接收和解码参数。    
            //snsapi_base   //snsapi_base    scope = snsapi_base（不弹出授权页面，直接跳转，只能获取用户 openid ）。  
            //snsapi_userinfo  弹出  

            let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
            window.location.href = authURL;
        }
        */

        wx_auth();
    }
}


async function refresh_settings() {
    await request('refresh_settings/', {
        zm_token: localStorage.user_token,
        _zm_post_type: 'ajax'
    }).then(res => {
        console.log('refresh_settings', res);
        request('get_share_sign/', {
            zm_token: localStorage.user_token,
            _zm_post_type: 'ajax',
            url: location.href
        }).then(res => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.rsm.appId, // 必填，公众号的唯一标识
                timestamp: res.rsm.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.rsm.nonceStr, // 必填，生成签名的随机串
                signature: res.rsm.signature, // 必填，签名
                jsApiList: ['onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',
                    'onMenuShareTimeline',
                    'updateAppMessageShareData',
                    'hideOptionMenu',
                    'showOptionMenu',
                    'hideMenuItems',
                    'showMenuItems',
                    'hideAllNonBaseMenuItem',
                    'showAllNonBaseMenuItem',
                ] // 必填，需要使用的JS接口列表
            });
            wx.ready(function () { //需在用户可能点击分享按钮前就先调用
                wx.updateAppMessageShareData({
                    title: '2021少数民族传统体育竞技', // 分享标题
                    desc: '邀你一起参与游戏，赢取现金红包！', // 分享描述
                    link: `http://youxi.haiqikj.com`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: './img/share_img_bg.png', // 分享图标
                    success: function () {
                        console.log('分享成功');
                    }
                })
            });
        })
    })
}

// function haveToken() {
//     let link = window.location.href
//     if (link.indexOf('token') < 0) {
//         window.location.href = 'http://youxi.haiqikj.com/index.html'
//     } else {
//         let token = getUrlParam('token')
//         location.setStorageSync('token', token)
//     }
// }

// // fetch封装
// function request(url, data) {
//     let formData = new FormData()
//     for (const key in data) {
//         if (Object.hasOwnProperty.call(data, key)) {
//             const element = data[key];
//             formData.append(`${key}`, `${element}`)
//         }
//     }
//     const result = fetch(`/apis/m/ajax/${url}`, {
//             method: 'POST',
//             mode: 'cors',
//             body: formData
//         }).then(res => res.json())
//         .then(json => {
//             return json
//         })
//     return result
// }